const express = require('express');
const path = require('path');
const formidable = require('formidable');
const { User } = require('../model/user')
const { Article } = require('../model/article')

const admin = express.Router();

admin.get('/login', (req, res) => {
  res.render('admin/login')
});

admin.get('/user', async (req, res) => {
  req.app.locals.currentLink = 'user';
  let page = req.query.page || 1;
  let pageSize = 2;
  let counts = await User.countDocuments({});
  let total = Math.ceil(counts / pageSize);
  let start = (page -1) * pageSize;
  let users = await User.find().limit(pageSize).skip(start)
  res.render('admin/user', {
    users,
    page,
    total
  })
});

admin.post('/login', async (req, res) => {
  const {email, password} = req.body;
  if (email.trim().length == 0 || password.trim().length == 0) {
    return res.status(400).render('admin/error', {msg: '邮箱或密码错误1'});
  }

  let user = await User.findOne({email});
  if (user) {
    if (user.password == password) {
      req.session.username = user.username;
      // res.send('登录成功')
      req.app.locals.userInfo = user;
      res.redirect('/admin/user')
    } else {
      res.status(400).render('admin/error', {msg: '密码错误'})
    }
  } else {
    res.status(400).render('admin/error', {msg: '邮箱或密码错误2'})
  }
  
  // res.redirect('/admin/user')
})

admin.get('/user-edit', async (req, res) => {
  req.app.locals.currentLink = 'user';
  const { message, id } = req.query

  if (id) {
    let user = await User.findOne({_id: id});
    res.render('admin/user-edit', {
      user,
      message,
      link: '/admin/user-modify?id=' + id,
      button: '修改'
    })
  } else {
    res.render('admin/user-edit', {
      message,
      link: '/admin/user-edit',
      button: '添加'
    })
  }

})

admin.post('/user-edit', async (req, res, next) => {
  if (!req.body.username || !req.body.email || !req.body.password || !req.body.role) {
    // res.redirect('/admin/user-edit?message=请输入完整')
    next(JSON.stringify({
      path: '/admin/user-edit',
      message: '请输入完整next'
    }))
    return;
  }

  let user = await User.findOne({email: req.body.email})

  if (user) {
    // res.redirect('/admin/user-edit?message=用户已存在')
    next(JSON.stringify({
      path: '/admin/user-edit',
      message: '用户已存在next'
    }))
    return;
  } else {
    await User.create(req.body)
  }
  res.redirect('/admin/user')
})


admin.post('/user-modify', async (req, res, next) => {
  const { id } = req.query;
  const body = req.body;
  let user = await User.findOne({_id: id});
  if (user.password == req.body.password) {
    await User.updateOne({_id: id}, {
      username: body.username,
      email: body.email,
      role: body.role,
      state: body.state
    })
    res.redirect('/admin/user')
  } else {
    next(JSON.stringify({
      path: '/admin/user-edit',
      message: '密码不对',
      id
    }))
  }
})

admin.get('/delete', async (req, res) => {
  const id = req.query.id;
  await User.findOneAndDelete({_id: id})
  res.redirect('/admin/user')
})


// 文章列表
admin.get('/article', async (req, res) => {
  req.app.locals.currentLink = 'article';
  // let articles = await Article.find().populate('author');
  let articles = await Article.find();
  res.render('admin/article.art', {
    articles
  })
  
});

// 文章编辑
admin.get('/article-edit', (req, res) => {
  req.app.locals.currentLink = 'article';
  res.render('admin/article-edit.art')
})

// 添加文章
admin.post('/article-add', (req, res) => {
  // 1.创建表单解析对象
  const form = new formidable.IncomingForm();
  // 2.配置上传文件的位置
  form.uploadDir = path.join(__dirname, '..', 'public', 'uploads');
  // 3.保留文件后缀
  form.keepExtensions = true;
  // 4.解析表单
  form.parse(req, async (err, fields, files) => {
    // fields 是普通表单数据  files是上传文件数据
    let imgpath = files.cover.path.split('public')[1]
    await Article.create({
      title: fields.title,
      author: fields.author,
      publishDate: fields.publishDate,
      cover: imgpath,
      content: fields.content
    })
    res.redirect('/admin/article')
  })
})
module.exports = admin;